'''
Created on Aug 22, 2009

@author: mkiyer
'''

from veggie.app.alignment.bowtie import Bowtie
import sys
import logging
import os
import glob
import re

def bowtie_best_lanes(root_path, dest_path, mode="single-best"):
    # make directory for results
    bowtie_cwd = dest_path
    if not os.path.exists(bowtie_cwd):
        logging.debug('Creating bowtie results path %s' % bowtie_cwd)
        os.makedirs(bowtie_cwd)
    
    # glob to get all the sequence files
    logging.debug('Running bowtie on lanes in sample..')
    fastq_files = glob.glob(os.path.join(root_path, "*_best_sequence.txt"))
    sorted_fastq = sorted(fastq_files)

    # regexp for getting beginning of filename to use as prefix
    # in output file
    prefix_re = re.compile(r'(.*)_best_sequence.txt')

    for fastq_file in sorted_fastq:
        m = prefix_re.match(os.path.basename(fastq_file))
        if not m:
            logging.critical("regexp match failed on file %s" % fastq_file)
        
        # get the quals param from the bowtie file
        analysis_id = m.group(1)
        quals_file = os.path.join(root_path, analysis_id + '_best_bowtiequals.txt')
        quals_fhd = open(quals_file)
        quals_param = quals_fhd.readline()
        quals_fhd.close()
        
        # construct output file name
        output_file = '%s_%s.txt' % (m.group(1), mode)
        logging.debug("file: %s quals: %s output_file: %s" % (fastq_file, quals_param, output_file))
        
        if os.path.exists(os.path.join(bowtie_cwd, output_file)):
            logging.debug("output file %s exists, skipping..." % output_file)
            continue
            
        # TODO: add support for paired-end, multi-map, etc
        # bowtie setup for single-best
        bowtie_options = {'-p': 8,
                          '--' + quals_param: None}   
        # create the app controller
        bowtie_app = Bowtie(cwd=bowtie_cwd, options=bowtie_options)
        bowtie_app.run_single_best(fastq_file, output_file)

if __name__ == '__main__':
    logging.basicConfig(filename="bowtie.log", 
                        format='%(asctime)s %(levelname)s %(message)s',
                        level=logging.DEBUG)
    #logging.basicConfig(level=logging.DEBUG)
    root_path = sys.argv[1]
    dest_path = sys.argv[2]
    bowtie_best_lanes(root_path, dest_path)
